﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ITD_VAPCF.NganQuy.BLL;
using ITD_VAPCF.NganQuy.ENTITY;
namespace ITD_VAPCF.NganQuy.GUI
{
    public partial class frmDuyeGiaoDich : Form
    {
        int Count = 0;
        bool Loaded = false;
        public frmDuyeGiaoDich()
        {
            InitializeComponent();
            for (int i = 0; i < CommonTable.dtDm_ChiNhanh.Rows.Count; i++)
            {
                cb_chinhanh.Items.Add(CommonTable.dtDm_ChiNhanh.Rows[i]["Ten_tat"]); 
            }
            cbTrangThaiGiaoDich.SelectedIndex = 0;
            cbTrangthaiKiemke.SelectedIndex = 0;
            cb_chinhanh.SelectedIndex = 0;
            dtpTuNgay.Value = Sys_Infor_SectionWorking.g_WorkingDate;
            dtpToiNgay.Value = Sys_Infor_SectionWorking.g_WorkingDate;
            dtgvBangKe.AutoGenerateColumns = false;
            LoadLoaiGiaoDich();
            tvwTreeView.Nodes[0].Checked = true;
            LoadAllGiaoDich();

        }
        private void LoadLoaiGiaoDich()
        {
            try
            {
                DataTable DMLoaiGiaoDich = NgayQuyBLL.Get_LoaiGiaoDich();

                tvwTreeView.Nodes.Add("ROOT", "Giao dịch", 1, 1);
                tvwTreeView.Nodes["ROOT"].NodeFont = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                tvwTreeView.Nodes["ROOT"].Nodes.Add("TV", "Thành viên", 0, 0);
                tvwTreeView.Nodes["ROOT"].Nodes["TV"].NodeFont = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                tvwTreeView.Nodes["ROOT"].Nodes.Add("TK", "Huy động vốn", 0, 0);
                tvwTreeView.Nodes["ROOT"].Nodes["TK"].NodeFont = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                tvwTreeView.Nodes["ROOT"].Nodes.Add("TD", "Tín dụng", 0, 0);
                tvwTreeView.Nodes["ROOT"].Nodes["TD"].NodeFont = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                tvwTreeView.Nodes["ROOT"].Nodes.Add("KT", "Kế toán", 0, 0);
                tvwTreeView.Nodes["ROOT"].Nodes["KT"].NodeFont = new System.Drawing.Font("Arial", 9.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                if (DMLoaiGiaoDich != null)
                {
                    for (int i = 0; i < DMLoaiGiaoDich.Rows.Count; i++)
                    {
                        string _Key = DMLoaiGiaoDich.Rows[i]["ma"].ToString().Trim();
                        string _Caption = DMLoaiGiaoDich.Rows[i]["ten"].ToString().Trim();
                        string _Group = DMLoaiGiaoDich.Rows[i]["ma_nhom"].ToString().Trim();
                        this.tvwTreeView.Nodes["ROOT"].Nodes[_Group].Nodes.Add(_Key, _Caption);
                    }
                }

            }
            catch (Exception ex)
            {
                Common.Messages.ShowError(ex.Message.ToString());
                Common.LogError.WriteLog(ex, this.Name, "LoadLoaiGiaoDich");
            }
        }
        DataTable dt;
        private void LoadAllGiaoDich()
        {
            dt = new DataTable();
            dt = NgayQuyBLL.DanhSachGiaoDich(dtpTuNgay.Value.ToString("yyyyMMdd"), dtpToiNgay.Value.ToString("yyyyMMdd"));
            dtgvBangKe.DataSource = dt.DefaultView;
            FilterData();
        }

        private void FilterData()
        {
            if (dt == null) return;
            string _Filter = "(1=1)";
            if (cbTrangThaiGiaoDich.SelectedIndex < 2)
            {
                _Filter += " and (trang_thai =" + cbTrangThaiGiaoDich.SelectedIndex + ")";
            }
            if (cbTrangthaiKiemke.SelectedIndex < 2)
                _Filter += " and (kiemke_tthai =" + cbTrangthaiKiemke.SelectedIndex + ")";

            if (txtSoCT.Text != "")
            {
                _Filter += "And (SoCT like '%" + txtSoCT.Text + "%')";
            }
            if (txtDienGiai.Text != "")
            {
                _Filter += "And (DienGiai like '%" + txtDienGiai.Text + "%')";
            }
            if (LoaiGD_MaString != "")
            {
                _Filter += LoaiGD_MaString;
            }
            _Filter += " and chinhanh_id = " + (cb_chinhanh.SelectedIndex + 1);
            dt.DefaultView.RowFilter = _Filter;
            dtgvBangKe.Refresh();
        }
        string LoaiGD_MaString = "";
        private void tvwTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (e.Node.Name == "ROOT")
                {
                    //Sử dụng biến Count để kiểm tra xem đã check hết các checkbox trên treeview hay chưa
                    //khi nào check xong hết mới load dữ liệu
                    Count = tvwTreeView.Nodes[0].Nodes.Count;
                    for (int i = 0; i < tvwTreeView.Nodes[0].Nodes.Count; i++)
                    {
                        tvwTreeView.Nodes[0].Nodes[i].Checked = e.Node.Checked;

                        Count--;
                    }
                }
                if (e.Node.Level == 1)
                {
                    Count = e.Node.Nodes.Count;
                    for (int j = 0; j < e.Node.Nodes.Count; j++)
                    {
                        tvwTreeView.Nodes[0].Nodes[e.Node.Index].Nodes[j].Checked = e.Node.Checked;
                        Count--;
                    }
                }
                //Do mỗi lần check vào một nút trên treeview thì hàm AfterCheck lại được gọi lại, nên phải kiểm tra 
                //xem Count đã == 0 hay chưa mới load dữ liệu
                if (Count == 0)
                {
                    LoaiGD_MaString = "";
                    for (int i = 0; i < tvwTreeView.Nodes[0].Nodes.Count; i++)
                    {
                        for (int j = 0; j < tvwTreeView.Nodes[0].Nodes[i].Nodes.Count; j++)
                        {
                            if (tvwTreeView.Nodes[0].Nodes[i].Nodes[j].Checked)
                                LoaiGD_MaString += "  loai_giao_dich_id = " + "'" + tvwTreeView.Nodes[0].Nodes[i].Nodes[j].Name + "' or ";
                        }
                    }
                    {
                        LoaiGD_MaString = " AND (" + LoaiGD_MaString + " loai_giao_dich_id = 256)";
                        FilterData();
                    }
                }
            }
            catch (Exception ex)
            {
                Common.Messages.ShowError(ex.Message.ToString());
                Common.LogError.WriteLog(ex, this.Name, "tvKyHan_AfterCheck");
            }
        }

        private void dtgvBangKe_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {

        }

        private void btnLamMoiDuLieu_Click(object sender, EventArgs e)
        {
            LoadAllGiaoDich();
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void dtgvBangKe_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (dtgvBangKe.CurrentRow == null) return;
                if (dtgvBangKe.Rows.Count == 0) return;
                string ID_Giao_Dich = dtgvBangKe.CurrentRow.Cells["ID"].Value.ToString().Trim();
                frmKKTM_ThuQuy frm = new frmKKTM_ThuQuy();
                frm.MaNhom = dtgvBangKe.CurrentRow.Cells["ma_nhom"].Value.ToString();
                frm.GiaoDichID = ID_Giao_Dich;
                frm.EntityGiaoDich = new ITD_VAPCF.NganQuy.ENTITY.TienMatGiaoDich
                                    (ID_Giao_Dich
                                    , dtgvBangKe.CurrentRow.Cells["loai_giao_dich_id"].Value.ToString()
                                    , dtgvBangKe.CurrentRow.Cells["loai_chung_tu"].Value.ToString()
                                    , dtgvBangKe.CurrentRow.Cells["SoCT"].Value.ToString()
                                    , Common.ConvertData.ToDouble(dtgvBangKe.CurrentRow.Cells["SoTien"].Value.ToString())
                                    , Common.ConvertData.ToDate(dtgvBangKe.CurrentRow.Cells["NgayGD"].Value.ToString())
                                    );
                if (dtgvBangKe.CurrentRow.Cells["loai_chung_tu"].Value.ToString().Trim() == "01")
                    frm.SumThu = Common.ConvertData.ToDouble(dtgvBangKe.CurrentRow.Cells["SoTien"].Value.ToString());
                else frm.SumChi = Common.ConvertData.ToDouble(dtgvBangKe.CurrentRow.Cells["SoTien"].Value.ToString());

                frm.ShowDialog();
            }
            catch
            {

            }
            btnLamMoiDuLieu_Click(null, null);
        }

        private void frmDuyeGiaoDich_Shown(object sender, EventArgs e)
        {
            Loaded = true;
        }

        private void dtpTuNgay_ValueChanged(object sender, EventArgs e)
        {
            if (Loaded)
                LoadAllGiaoDich();
        }

        private void txtSoCT_Click(object sender, EventArgs e)
        {
            FilterData();
        }

        private void cbTrangThaiGiaoDich_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Loaded) FilterData();
        }

        private void btnKKTM_Click(object sender, EventArgs e)
        {
            dtgvBangKe_DoubleClick(null, null);
            
        }

        private void btnIn_Click(object sender, EventArgs e)
        {
            try
            {
                if (dtgvBangKe.CurrentRow == null) return;
                if (dtgvBangKe.Rows.Count == 0) return;
                string ID_Giao_Dich = dtgvBangKe.CurrentRow.Cells["ID"].Value.ToString().Trim();
                frmKKTM_ThuQuy frm = new frmKKTM_ThuQuy();
                frm.MaNhom = dtgvBangKe.CurrentRow.Cells["ma_nhom"].Value.ToString();
                frm.GiaoDichID = ID_Giao_Dich;
                frm.EntityGiaoDich = new ITD_VAPCF.NganQuy.ENTITY.TienMatGiaoDich
                                    (ID_Giao_Dich
                                    , dtgvBangKe.CurrentRow.Cells["loai_giao_dich_id"].Value.ToString()
                                    , dtgvBangKe.CurrentRow.Cells["loai_chung_tu"].Value.ToString()
                                    , dtgvBangKe.CurrentRow.Cells["SoCT"].Value.ToString()
                                    , Common.ConvertData.ToDouble(dtgvBangKe.CurrentRow.Cells["SoTien"].Value.ToString())
                                    , Common.ConvertData.ToDate(dtgvBangKe.CurrentRow.Cells["NgayGD"].Value.ToString())
                                    );
                if (dtgvBangKe.CurrentRow.Cells["loai_chung_tu"].Value.ToString().Trim() == "01")
                    frm.SumThu = Common.ConvertData.ToDouble(dtgvBangKe.CurrentRow.Cells["SoTien"].Value.ToString());
                else frm.SumChi = Common.ConvertData.ToDouble(dtgvBangKe.CurrentRow.Cells["SoTien"].Value.ToString());

                frm.InChungTu();
            }
            catch
            {

            }
        }

        private void sửaGiaoDịchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtgvBangKe_DoubleClick(null, null);
        }

        private void inBảngKêToolStripMenuItem_Click(object sender, EventArgs e)
        {
            btnIn_Click(null, null);
        }

        private void thêmMớiGiaoDịchToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void đánhDấuĐãKiểmKêToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dtgvBangKe.EndEdit();
            int count = 0;
            KKTienMat _entityTienMat = new KKTienMat();
            KKTienMatBLL objNQ_GiaoDich = new KKTienMatBLL(CommonVAPCF.GlobalVariables.g_strConnectionMsSql);
            for (int i = 0; i < dtgvBangKe.RowCount; i++)
            {
                int chon = 0;
                if (!int.TryParse(dtgvBangKe["Chon", i].Value.ToString(), out chon)) continue;
                if ((dtgvBangKe["Chon", i].Value == null) ||
                  chon == 0) continue;
                if ((int)dtgvBangKe["kiemke_tthai", i].Value == 1) continue;
                string ID_Giao_Dich = dtgvBangKe["ID", i].Value.ToString().Trim();
                TTKhachHang EntityKhachHang = new TTKhachHang();
                EntityKhachHang = objNQ_GiaoDich.Get_ThongTinKhachHang2(ID_Giao_Dich, dtgvBangKe["ma_nhom", i].Value.ToString());
                if (ID_Giao_Dich != "")
                {
                    objNQ_GiaoDich.InsUpd_ThongTinKhachHang(ID_Giao_Dich, EntityKhachHang, "Ins");
                    count++;
                }
            }
            if (count > 0)
            {
                LoadAllGiaoDich();
                btnCheckAll.Checked = true;
            }
            else CommonVAPCF.MessagesReturn.ShowDialog("Bạn chưa chọn giao dịch nào để đánh dấu");
        }

        private void cbTrangthaiKiemke_Click(object sender, EventArgs e)
        {



        }

        private void btnCheckAll_Click(object sender, EventArgs e)
        {
            btnCheckAll.Checked = !btnCheckAll.Checked;
            if (dtgvBangKe.RowCount > 0)
            {
                for (int i = 0; i < dtgvBangKe.RowCount; i++)
                    if (btnCheckAll.Checked)

                        dtgvBangKe["Chon", i].Value = 1;
                    else

                        dtgvBangKe["Chon", i].Value = 0;
            }
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            dtgvBangKe.EndEdit();
            int count = 0;
            KKTienMat _entityTienMat = new KKTienMat();
            KKTienMatBLL objNQ_GiaoDich = new KKTienMatBLL(CommonVAPCF.GlobalVariables.g_strConnectionMsSql);
            for (int i = 0; i < dtgvBangKe.RowCount; i++)
            {
                int chon = 0;
                if (!int.TryParse(dtgvBangKe["Chon", i].Value.ToString(), out chon)) continue;
                if ((dtgvBangKe["Chon", i].Value == null) ||
                  chon == 0) continue;
                if ((int)dtgvBangKe["kiemke_tthai", i].Value == 0) continue;
                string ID_Giao_Dich = dtgvBangKe["ID", i].Value.ToString().Trim();
                TTKhachHang EntityKhachHang = new TTKhachHang();
                EntityKhachHang = objNQ_GiaoDich.Get_ThongTinKhachHang2(ID_Giao_Dich, dtgvBangKe["ma_nhom", i].Value.ToString());
                if (ID_Giao_Dich != "")
                {
                    objNQ_GiaoDich.Delete_ThongTinKhachHang(ID_Giao_Dich);
                    count++;
                }
            }
            if (count > 0)
            {
                LoadAllGiaoDich();
                btnCheckAll.Checked = true;
            }
            else CommonVAPCF.MessagesReturn.ShowDialog("Bạn chưa chọn giao dịch nào để đánh dấu");

        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            dtgvBangKe.EndEdit();
            tolBoDau.Enabled = false;
            tolDanhDau.Enabled = false;
            for (int i = 0; i < dtgvBangKe.RowCount; i++)
            {
                int _chon = 0;
                if (!int.TryParse(dtgvBangKe["Chon", i].Value.ToString(),out _chon)) continue;
                if (_chon == 1)
                {
                    if ((int)dtgvBangKe["kiemke_tthai", i].Value == 0) tolDanhDau.Enabled = true;
                    if ((int)dtgvBangKe["kiemke_tthai", i].Value == 1) tolBoDau.Enabled = true;
                }
            }
        }

        private void btnXoaGiaoDich_Click(object sender, EventArgs e)
        {
            if (dtgvBangKe.Rows.Count == 0) return;
            if (MessageBox.Show("Bạn có thực sự muốn xóa giao dịch được chọn?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
            dtgvBangKe.EndEdit();
            int Count = dtgvBangKe.Rows.Count - 1;
            for (int i = dtgvBangKe.Rows.Count - 1; i >= 0; i--)
            {
                if (Common.ConvertData.ToInt(dtgvBangKe["Chon", i].Value) == 1)
                {
                    string ID_Giao_Dich = dtgvBangKe["ID", i].Value.ToString().Trim();
                    KKTienMatBLL objNQ_GiaoDich = new KKTienMatBLL(CommonVAPCF.GlobalVariables.g_strConnectionMsSql);
                    objNQ_GiaoDich.Delete(ID_Giao_Dich);
                    objNQ_GiaoDich.Delete_ThongTinKhachHang(ID_Giao_Dich);
                    dtgvBangKe["kiemke_tthai", i].Value = 0;
                }
            }
            btnLamMoiDuLieu_Click(null, null);
        }

        private void txtSoCT_TextChanged(object sender, EventArgs e)
        {
            FilterData();
        }

        private void cbTrangThaiGiaoDich_Click(object sender, EventArgs e)
        {

        }

    }
}
